package com.sysphysic.aiotsystem.controller;

import com.sysphysic.aiotsystem.service.PahoMqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LedController {

    @Autowired
    private PahoMqttService mqttService;

    @PostMapping("/led/{color}/{action}")
    public ResponseEntity<Map<String, Object>> controlLed(
            @PathVariable String color,
            @PathVariable String action) {

        Map<String, Object> response = new HashMap<>();

        // 参数验证
        if (!color.equals("red") && !color.equals("blue")) {
            response.put("success", false);
            response.put("message", "无效的颜色参数，请使用 'red' 或 'blue'");
            return ResponseEntity.badRequest().body(response);
        }

        if (!action.equals("on") && !action.equals("off")) {
            response.put("success", false);
            response.put("message", "无效的动作参数，请使用 'on' 或 'off'");
            return ResponseEntity.badRequest().body(response);
        }

        boolean success = mqttService.sendControlMessage("led_" + color, action);

        response.put("success", success);
        response.put("message", success ?
                String.format("%s LED %s 命令发送成功", color, action) :
                "命令发送失败，请检查MQTT连接");
        response.put("device", "led_" + color);
        response.put("action", action);
        response.put("timestamp", System.currentTimeMillis());
        response.put("mqtt_connected", mqttService.isConnected());

        return success ? ResponseEntity.ok(response) :
                ResponseEntity.internalServerError().body(response);
    }

    @PostMapping("/red/on")
    public ResponseEntity<Map<String, Object>> turnOnRedLed() {
        return controlLed("red", "on");
    }

    @PostMapping("/red/off")
    public ResponseEntity<Map<String, Object>> turnOffRedLed() {
        return controlLed("red", "off");
    }

    @PostMapping("/blue/on")
    public ResponseEntity<Map<String, Object>> turnOnBlueLed() {
        return controlLed("blue", "on");
    }

    @PostMapping("/blue/off")
    public ResponseEntity<Map<String, Object>> turnOffBlueLed() {
        return controlLed("blue", "off");
    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("service", "STM32 LED控制服务");
        status.put("status", "运行中");
        status.put("mqtt_connected", mqttService.isConnected());
        status.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(status);
    }

}
